package com.ruoyi.web.controller.blog;

import com.ruoyi.blog.domain.Article;
import com.ruoyi.blog.domain.Comment;
import com.ruoyi.blog.domain.Like;
import com.ruoyi.blog.domain.Meta;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Tina
 * @Date 2021-6-2
 */
@RestController
@RequestMapping("/article/")
public class ArticleController extends BaseController {


    @Autowired
    private RedisCache redisCache;
    private String[] img = {
            "https://ftp.bmp.ovh/imgs/2021/06/4a9447afe153ce1e.jpg", "https://ftp.bmp.ovh/imgs/2021/06/f60c59c52dfb5243.jpg",
            "https://i.bmp.ovh/imgs/2019/07/80ce3d8f2395d3e1.jpg", "https://ftp.bmp.ovh/imgs/2020/07/455a6c6a0ce581ca.jpg"
    };
    private String[] auther = {
            "https://ftp.bmp.ovh/imgs/2021/06/fdb98ed6e43fb1be.png", "https://ftp.bmp.ovh/imgs/2021/06/f49563b6815afcca.png",
            "https://ftp.bmp.ovh/imgs/2021/06/64966f836af2278c.jpg", "https://ftp.bmp.ovh/imgs/2021/06/a17bccf3e11e3bac.jpg"
    };

    /**
     * 缓存文章
     */
    private void cacheAricle() {
        redisCache.deleteObject("cacheAricle");
        List<Article> list = new ArrayList<>();
        List<String> tags = new ArrayList<>();
        tags.add("Java");
        tags.add("MySQL");
        tags.add("SpringBoot");
        tags.add("博客");
        Integer[] type = {0, 1};
        for (long i = 1; i < 20; i++) {
            Article article = new Article();
            Meta meta = new Meta();
            article.setId(i);
            article.setTitle("文章" + i);
            article.setContent("作者：匿名用户\n" +
                    "链接：https://www.zhihu.com/question/282616500/answer/1704316927\n" +
                    "来源：知乎\n" +
                    "著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。\n" +
                    "\n" +
                    "中高端开始迪卡侬不如捷安特。迪卡侬基础的专业级公路车RCR系列除了性价比之外真的打不过TCR。坐拥RCR900CF和TCR Advanced 1+。价格上TCR比RCR贵了一倍，4300新币对比2150新币。配置上面，RCR是Tiagra级别的RS100的铝合金轮组，甚至都不兼容真空胎。这点我个人不喜欢。基本上是禧玛诺105大套，KOM配置（50/34压缩牙盘，11/34飞轮组），圈刹。TCR的轮组是SLR-2碳纤维轮组，ultegra大套，液压碟刹。（好吧这里有一个坑是我买车的时候忽视的，这款2021年的新TCR居然用老的Ultegra曲柄，但是表现上其实被没有太大的差异，至少我感觉不出来）。Compact Pro配置（52/36牙盘，11/30飞轮）。2021新TCR的车架气动更加好一些，轻一些。个人感觉TCR的几何更加舒适，除了捷安特的坐垫对我而言有点宽，迪卡侬的又有一些长。言归正传，TCR在气动上做出来的优化还是可见的。破风效果确实比我的RCR900强，当然，也有我的轮组的原因。RCR则很中规中矩的设计，很多新技术也没有运用到车子上。估计例子，现在圈刹都开始用Direct Mount了，RCR虽然是用了Dual Pivot的圈刹但是还是单点安装。这是我比较不喜欢的一个点。但是刹车的性能和碟刹确实没法比啊。车架刚性表现还是TCR好一些。TCR在我高输出的情况下车架弹性形变比RCR小很多。而且新加坡迪卡侬宣称RCR最大承重100公斤，虽然鄙人略超100公斤也没什么问题，但比起号称130公斤毫无畏惧的TCR还是弱了些，不只是气势上。至于透露的信号么，自行感受。好了，这两辆车都是我环岛大杀器。我都很喜欢。RCR900胜在性价比，TCR胜在性能和表现。RCR我直接就是裸奔，TCR我可是花了好几个小时贴了膜的，毕竟差不多一个月工资和半个月工资还是有区别的。两家怎么选，看你自己。但是迪卡侬的车是真的重，越低端越重。其实真的就看自己的喜好就好了。迪卡侬么，涂装还是蛮丑的，毕竟，是高卢雄鸡的审美哈哈哈。");
            article.setDescript("描述:aaaaa" + i);
            article.setTags(tags);
            article.setCreateTime(System.currentTimeMillis());
            int index = (int) (Math.random() * img.length);
            int typeIndex = (int) (Math.random() * type.length);
            article.setType(type[typeIndex]);
            article.setCover(img[index]);
            meta.setComments(1);
            meta.setLikes(12311);
            meta.setViews(0);
            article.setMeta(meta);
            list.add(article);
        }
        redisCache.setCacheList("cacheAricle", list);
    }

    /**
     * 文章列表
     *
     * @param current_page
     * @return
     */
    @GetMapping("list")
    public TableDataInfo list(Long current_page) {
        //  cacheAricle();
        List<Article> cacheList = redisCache.getCacheList("cacheAricle");
        return getDataTable(cacheList);
    }

    /**
     * 文章ID获取详情
     *
     * @param articleId 文章ID
     * @return List
     */
    @GetMapping("{articleId}")
    public AjaxResult getInfo(@PathVariable("articleId") Long articleId) {
        List<Article> cacheList = redisCache.getCacheList("cacheAricle");
        List<Like> likeCache = redisCache.getCacheList("likeCache:" + articleId);
        for (Article article : cacheList) {
            if (article.getId().equals(articleId)) {
                article.getMeta().setLikes(
                        likeCache.stream().filter(l -> l.getType().equals(0) && l.getLikeId().equals(article.getId())).collect(Collectors.toList()).size());

                return AjaxResult.success(article);
            }
        }
        return AjaxResult.success();
    }

    /**
     * 评论列表
     *
     * @param sort      排序{new:最新，heat:最热}
     * @param articleId 文章ID
     * @return List
     */
    @GetMapping("comment")
    public TableDataInfo comment(String sort, Long articleId) {
        startPage();
        List<Comment> comments = collectComment(sort, articleId);
        List<Comment> pList = comments.stream().filter(c -> c.getPid() == 0).collect(Collectors.toList());
        pList.stream().forEach(p -> {
            p.setChildren(comments.stream().filter(c -> p.getId().equals(c.getPid())).collect(Collectors.toList()));
        });
        return getDataTable(pList);
    }

    /**
     * 从缓存中获取数据
     *
     * @param sort      排序
     * @param articleId 文章ID
     * @return List
     */
    private List<Comment> collectComment(String sort, Long articleId) {
        //   cacheComment();
        List<Comment> cacheComment = redisCache.getCacheList("cacheComment:" + articleId);
        List<Like> likeCache = redisCache.getCacheList("likeCache:" + articleId);

        if (cacheComment.size() > 0) {
            if (StringUtils.equals(Constants.HEAT, sort)) {
                cacheComment = cacheComment.stream().sorted(Comparator.comparing(Comment::getLike).reversed()).collect(Collectors.toList());
            } else {
                cacheComment = cacheComment.stream().sorted(Comparator.comparing(Comment::getCreateTime).reversed()).collect(Collectors.toList());
            }
        }
        for (Comment c : cacheComment) {
            for (Like l : likeCache) {
                if (l.getType().equals(1) && l.getLikeId().equals(c.getId())) {
                    c.setLike(
                            likeCache.stream().filter(like ->
                                    like.getLikeId().equals(c.getId())
                            ).collect(Collectors.toList()).size()
                    );
                }
            }
        }

        return cacheComment;
    }

    /**
     * 新增评论
     *
     * @return
     */
    @PostMapping("comment")
    public AjaxResult addComment(@RequestBody Comment comment) {
        comment.setCreateTime(System.currentTimeMillis());
        comment.setLike(0);
        final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        final String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        comment.setIp(ip);
        comment.setLocation(AddressUtils.getRealAddressByIP(ip));
        comment.setOs(userAgent.getOperatingSystem().getName());
        comment.setStatus("0");
        comment.setAuthor("https://ftp.bmp.ovh/imgs/2021/06/38f2aa7ed071fbc4.png");
        comment.setId(System.currentTimeMillis());
        Long rpush = redisCache.rpush("cacheComment:" + comment.getArticleId(), comment);
        return toAjax(Math.toIntExact(rpush));
    }

    /**
     * 点赞
     *
     * @param like
     * @return
     */
    @PostMapping("like")
    public AjaxResult like(@RequestBody Like like) {
        likePack(like);
        redisCache.rpush("likeCache:" + like.getArticleId(), like);
        return AjaxResult.success(like);
    }

    private void likePack(Like like) {
        final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        final String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        like.setIp(ip);
        like.setLocation(AddressUtils.getRealAddressByIP(ip));
        like.setOs(userAgent.getOperatingSystem().getName());
        like.setId(System.currentTimeMillis());
        like.setCreateTime(System.currentTimeMillis());
        like.setStatus("0");
    }

}
